using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using OpenComposite.EII.Repository;
using OpenComposite.Repository.Properties;
using System.Xml.Schema;
using System.IO;
using System.Xml;

namespace OpenComposite.EII.RepositoryUIs
{
	public partial class UCWebMethod : RepositoryItemUI
	{
		#region Initialization
		public UCWebMethod(IServiceProvider serviceProvider)
			: base(serviceProvider)
		{
			InitializeComponent();

			init();
		}
		private void init()
		{
		}
		#endregion

		#region Public Members

		#region Properties
		public override IRepositoryItem RepositoryItem
		{
			get
			{
				save();
				return _webMethod;
			}
			set
			{
				base.RepositoryItem = value;
				if ( value is WebMethod ) {
					_webMethod = (WebMethod)value;
					load();
				}
			}
		}

		public override string TypeText
		{
			get { return Resources.sWebMethod; }
		}

		public override string TypeDescription
		{
			get { return ""; }
		}
		#endregion

		#endregion

		#region Private Members

		#region Variables
		private WebMethod _webMethod = null;
		#endregion

		#region Methods

		private void showSchema(XmlSchema schema, string formText)
		{
			XmlDocument xd = new XmlDocument();
			using ( StringWriter sw = new StringWriter() ) {
				schema.Write(sw);
				xd.LoadXml(sw.ToString());
			}
			formXmlViewer XmlViewer = new formXmlViewer();
			XmlViewer.XmlDocument = xd;
			XmlViewer.Text = formText;
			XmlViewer.ShowDialog();
		}

		private void load()
		{
			if ( _webMethod == null )
				return;

			_webMethod.Reload();

			txtName.Text = _webMethod.Name;
			txtDesc.Text = _webMethod.Description;

			txtInput.Text = _webMethod.InputTypeName;
			txtOutput.Text = _webMethod.OutputTypeName;

			usedByHierarchyWebMethod.RepositoryItem = this.RepositoryItem as RepositoryItemBaseEx;
		}
		private void save()
		{
			if ( _webMethod == null )
				_webMethod = new WebMethod();

			_webMethod.Reload();

			_webMethod.Name = txtName.Text;
			_webMethod.Description = txtDesc.Text;
		}
		#endregion

		#region Event Handlers
		private void btnViewInput_Click(object sender, EventArgs e)
		{
			showSchema(_webMethod.InputSchema, string.Format("Input Contract for Web Method \"{0}\"", _webMethod.Name));
		}

		private void btnViewOutput_Click(object sender, EventArgs e)
		{
			showSchema(_webMethod.OutputSchema, string.Format("Output Contract for Web Method \"{0}\"", _webMethod.Name));
		}
		#endregion

		private void txtName_KeyPress(object sender, KeyPressEventArgs e)
		{
			if ( e.KeyChar < (char)32 ) return;
			e.Handled = !Helpers.IsValidCharForName(e.KeyChar);
		}

		#endregion
	}
}
